package com.lmbsvn.core.shiro.filter;

import com.lmbsvn.core.bean.ExceptionInfo;
import com.lmbsvn.core.shiro.bean.UsernamePasswordCaptchaToken;
import net.sf.json.JSONObject;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;

/**
 * 继承 Shiro FormAuthenticationFilter
 * 重写 onAccessDenied 方法,目的 Ajax请求Session超时，返回json数据
 * 重写AuthenticationToken,目的在于添加验证码参数
 * @author lumingbao
 */
public class MyFormAuthenticationFilter extends FormAuthenticationFilter{
	
	public static final String DEFAULT_CAPTCHA_PARAM = "captcha";

	private String captchaParam = DEFAULT_CAPTCHA_PARAM;

	public String getCaptchaParam() {
		return captchaParam;
	}

	protected String getCaptcha(ServletRequest request) {
		return WebUtils.getCleanParam(request, getCaptchaParam());
	}

	public String getSuccessUrl(){
		return super.getSuccessUrl();
	}

	@Override
	protected void issueSuccessRedirect(ServletRequest request, ServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		WebUtils.issueRedirect(request, response, getSuccessUrl());
	}

	@Override
	protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
		String username = getUsername(request);
		String password = getPassword(request);
		String captcha = getCaptcha(request);
		boolean rememberMe = isRememberMe(request);
		String host = getHost(request);
		return new UsernamePasswordCaptchaToken(username, password, rememberMe, host, captcha);
	}

	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		if (isLoginRequest(request, response)) {
            if (isLoginSubmission(request, response)) {
                return executeLogin(request, response);
            } else {
                return true;
            }
        } else {
        	//判断是否为Ajax请求
        	if("XMLHttpRequest".equalsIgnoreCase(((HttpServletRequest)request).getHeader("X-Requested-With"))) {
        		ExceptionInfo info = new ExceptionInfo();
        		info.setIsSessionOut(true);//设置session超时属性
        		JSONObject josn = JSONObject.fromObject(info);//将对象转换为json对象
            	response.setCharacterEncoding("UTF-8");
                PrintWriter out = response.getWriter();
                out.println(josn.toString());
                out.flush();
                out.close();
        	}else{
        		saveRequestAndRedirectToLogin(request, response);
        	}
            return false;
        }
	}
}
